# -*- coding:utf-8 -*-
'''
# Author: xiguan
# Mail: xiguan.teng@qq.com
# -----
# Last Modified: 2022-05-11 13:20:05
# Modified By: xiguan
# -----
# Copyright (c) 2022 XiGuan Inc.
# 
# No Bug No error No warning.
# -----
'''
import email
import random
import time
import smtplib

from pickle import dumps, loads
from flask import Blueprint, render_template, request, session, redirect
from config import db_session

from entity.User import User
from email.mime.text import MIMEText
from email.utils import formataddr

user = Blueprint('user',__name__)


# 跳转登陆页面
@user.route('/go_login/')
def go_login():
    print("go_login success call")
    return render_template("login.html")

# 登陆
@user.route("/login_do", methods=['POST'])
def login_do():
    # 获取用户名跟密码
    print("login_do success call")
    username = request.form.get('username')
    passwd = request.form.get('passwd')
    # print(username, passwd)
    # 查询用户
    user_find = list(db_session.query(User).filter_by(username=username))

    if len(user_find) == 0:
        return {"status" : "NO"}
    
    user_first = user_find[0]

    if user_first.password == passwd:
        session["user"] = dumps(user_first)
        return {"status" : "OK"}
    else:
        return {"status" : "NO"}

# 跳转注册
@user.route("/go_register/")
def go_register():
    print("go_register success call")
    return render_template("register.html")

# 跳转到index
@user.route("/go_index/")
def go_index():
    print("go_index success call")
    cur_user = session.get("user")
    # for i in cur_user:
    #     print(i)
    if cur_user is None:
        return render_template('login.html')
    else:
        return render_template('index.html', user=loads(cur_user))

# 判断邮箱是否存在
@user.route("/is_exist")
def is_exist():
    print("is_exist success call")
    email_get = request.args.get('email')
    # print(email_get)
    user_find = list(db_session.query(User).filter_by(username=email_get))
    # 如果长度为 0 ，表示该邮箱还未注册
    if len(user_find) == 0:
        return "False"
    # 长度不为 0 ，说明，该邮箱已经注册
    elif len(user_find) > 0:
        return "True"

# def create_code():
#     chapter_len: int = 6
#     chapter_str: str = ""
#     for i in range(0, chapter_len):
#         r: int = random.randint(0,9)
#         chapter_str = chapter_str + str(r)
#     return chapter_str

# 发送验证码到邮箱
@user.route('/get_vercode')
def get_chapter():
    print("get_vercode success call")
    global chapter
    username = request.args.get('username')
    my_sender = 'xiguan.teng@qq.com'
    my_pass = 'oxkyjvgqzizoddaa'
    my_user = username
    status = "OK"

    chapter_len: int = 6
    chapter_str: str = ""
    for i in range(0, chapter_len):
        r: int = random.randint(0,9)
        chapter_str = chapter_str + str(r)
    chapter = chapter_str
    # chapter = create_code()
    try:
        # 右键内容
        msg = MIMEText('尊敬的用户，你的注册验证码为：' + chapter , 'plain', 'utf-8')
        msg['From'] = formataddr(["XIGUAN", my_sender])
        msg['To'] = formataddr(["unknow", my_user])
        msg['Subject'] = "FTP云盘用户注册注册"
        server = smtplib.SMTP_SSL("smtp.qq.com", 465)
        server.login(my_sender, my_pass)
        server.sendmail(my_sender, [my_user, ], msg.as_string())
        server.quit()
    except Exception:
        status = "fail"
    # print(time.time())
    return {"status": status, "chapter": chapter, "timestamp": time.time()}

# 注册
@user.route('/register_do', methods=['POST'])
def do_register():
    print("register_do success call")
    try:
        # 获取输入的用户名
        username = request.form.get('email')
        # 获取输入的密码
        password = request.form.get('password')
        # print(username, password)
        # 根据用户的邮箱和密码创建一个用户
        register_user = User(username, password)
        # 向数据库中创建用户
        # print(register_user.username, register_user.password)
        db_session.add(register_user)
        # print(2)
        # 提交
        db_session.commit()
        # print(3)
    except Exception as e:
        db_session.rollback()
        return "NO"
    return "OK"